<template>
  <div>
    <ContentWrap>
      <div class="flex flex-justify-between">
        <div class="w-350px">
          <SubTitle title="目录" />
          <div id="draggable-box">
            <div v-for="(menu, menuIndex) in menuList" :key="menuIndex" class="mt-12px">
              <div v-if="menu.show">
                {{ menu.dataObjectName }}
              </div>
            </div>
          </div>
          <div class="mt-30px">
            <SubTitle title="默认查询" />
          </div>
          <el-form label-position="top">
            <el-form-item label="数据保护标准">
              <el-select
                v-model="defaultQuery.template"
                clearable
                placeholder="默认全部数据标准"
                @change="defaultQuery.classification = defaultQuery.template"
              >
                <el-option
                  v-for="(template, templateIndex) in templateList"
                  :key="templateIndex"
                  :label="template.dataStandardName"
                  :value="template.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分类">
              <el-cascader
                v-model="defaultQuery.classification"
                placeholder="默认全部分类"
                :props="classificationCascaderProps"
                :options="classificationList"
                filterable
                clearable
                @change="handleClassificationChange"
              />
            </el-form-item>
            <el-form-item label="分类展示级别">
              <el-select
                v-model="defaultQuery.showClassGrade"
                clearable
                placeholder="默认全部展示级别"
              >
                <el-option
                  v-for="(grade, gradeIndex) in gradeList"
                  :key="gradeIndex"
                  :label="grade.label"
                  :value="grade.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="等级">
              <el-select v-model="defaultQuery.level" clearable placeholder="默认全部等级">
                <el-option
                  v-for="(level, levelIndex) in levelList"
                  :key="levelIndex"
                  :label="level.levelName"
                  :value="level.levelCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属组织机构">
              <el-cascader
                v-model="defaultQuery.dept"
                clearable
                placeholder="默认全部归属机构"
                :options="deptList"
                :props="cascaderProps"
                filterable
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
            <el-form-item label="所属机构展示级别">
              <el-select
                v-model="defaultQuery.showDeptGrade"
                clearable
                placeholder="默认全部展示级别"
              >
                <el-option
                  v-for="(grade, gradeIndex) in gradeList"
                  :key="gradeIndex"
                  :label="grade.label"
                  :value="grade.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="所属应用系统">
              <el-cascader
                v-model="defaultQuery.sys"
                placeholder="默认全部归属系统"
                :props="systemCascaderProps"
                :options="systemList"
                filterable
                :filter-method="sysFilterMethod"
                clearable
            /></el-form-item>
            <el-form-item label="应用系统展示级别">
              <el-select
                v-model="defaultQuery.showSysGrade"
                clearable
                placeholder="默认全部展示级别"
              >
                <el-option
                  v-for="(grade, gradeIndex) in gradeList"
                  :key="gradeIndex"
                  :label="grade.label"
                  :value="grade.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="展示数量">
              <ns-input type="number" v-model="defaultQuery.number" placeholder="默认展示数量为5" />
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never" class="chart-wrap">
          <div class="text-center font-size-24px">
            {{ preData.name }}
          </div>
          <div id="draggable-menu">
            <div v-for="(menu, menuIndex) in menuList" :key="menuIndex" class="mb-22px">
              <div v-if="menu.show">
                <SubTitle :title="menu.dataObjectName" />
                <div :id="`chart-box${menuIndex}`">
                  <div v-for="(viewItem, viewIndex) in menu.view" :key="viewIndex" class="mb-12px">
                    <div v-if="viewItem.chartsType === 'Table'">
                      <el-table :data="tableData" style="width: 100%" :span-method="SpanMethod">
                        <el-table-column label="" width="150">
                          <template #default>
                            <div> {{ menu.dataObjectName }} </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="templateName" label="" width="150" />
                        <el-table-column label="" width="150">
                          <template #default="scope">
                            <div v-if="scope.$index !== 0">
                              <!-- <div v-if="scope.$index % 4 === 1"> 数据源 </div> -->
                              <div v-if="scope.$index % 4 === 1"> 数据表 </div>
                              <div v-if="scope.$index % 4 === 2"> 数据表字段 </div>
                              <div v-if="scope.$index % 4 === 3"> 文件资产 </div>
                            </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="total" label="" width="150" />
                        <el-table-column
                          :label="tableColumn"
                          v-for="(tableColumn, tableColumnIndex) in viewItem.others"
                          :key="tableColumnIndex"
                        >
                          <el-table-column
                            :prop="`${dataTypeMap.get(tableColumn)}1`"
                            label="机构一"
                            width="120"
                          />
                          <el-table-column
                            :prop="`${dataTypeMap.get(tableColumn)}2`"
                            label="机构二"
                            width="120"
                          />
                          <el-table-column
                            :prop="`${dataTypeMap.get(tableColumn)}3`"
                            label="机构三"
                            width="120"
                          />
                          <el-table-column
                            :prop="`${dataTypeMap.get(tableColumn)}4`"
                            label="机构四"
                            width="120"
                          />
                          <el-table-column
                            :prop="`${dataTypeMap.get(tableColumn)}5`"
                            label="机构五"
                            width="120"
                          />
                        </el-table-column>
                      </el-table>
                    </div>
                    <div v-if="viewItem.chartsType === 'Pie'">
                      <Echart :height="300" :options="pieOptionsData" />
                    </div>
                    <div v-if="viewItem.chartsType === 'Bar'">
                      <Echart :height="300" :options="barOptionsData" />
                    </div>
                    <div v-if="viewItem.chartsType === 'Line'">
                      <Echart :height="300" :options="lineOptionsData" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div class="mt-20px text-center" v-if="preData.tempId">
        <el-button type="primary" @click="cancel">上一步</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
      <div class="mt-20px text-center" v-if="preData.id">
        <el-button type="primary" @click="router.back()">返回</el-button>
        <el-button type="primary" @click="updateReport">保存</el-button>
      </div>
    </ContentWrap>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import SubTitle from '@/components/SubTitle/index.vue'
import Sortable from 'sortablejs'
import * as reportManageApi from '@/api/report/reportManage/index'
import * as reportTempApi from '@/api/report/reportTemp/index'
import { EChartsOption } from 'echarts'
import { barOptions, lineOptions, pieOptions } from '@/views/report/display/echarts-data'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { handleTree } from '@/utils/tree'
import { sysFilterMethod } from '@/utils/selectFilter'

const route = useRoute()
const router = useRouter()
const preData = ref(route.query)
const defaultQuery = ref({
  template: '',
  classification: '',
  showClassGrade: '',
  level: '',
  dept: '',
  showDeptGrade: '',
  sys: '',
  showSysGrade: '',
  number: 5
})

/** 分类选项修改 */
const handleClassificationChange = (value) => {
  if (!value) {
    return
  }
  let parentId = null
  for (let i = 0; i < classificationList.value.length; i++) {
    if (checkParent(classificationList.value[i], value)) {
      parentId = classificationList.value[i].id
      break
    }
  }
  defaultQuery.value.template = parentId
}

/** 寻找分类对应的数据保护标准 */
function checkParent(data, id) {
  if (data.id != id) {
    if (data.children && data.children.length > 0) {
      let flag = false
      for (let i = 0; i < data.children.length; i++) {
        flag |= checkParent(data.children[i], id)
      }
      return flag
    } else {
      return false
    }
  } else {
    return true
  }
}

const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const gradeList = [
 {
    label: '一级',
    value: '1'
  },
  {
    label: '二级',
    value: '2'
  },
  {
    label: '三级',
    value: '3'
  },
    {
    label: '四级',
    value: '4'
  },
    {
    label: '五级',
    value: '5'
  },
    {
    label: '六级',
    value: '6'
  },
    {
    label: '七级',
    value: '7'
  },
    {
    label: '八级',
    value: '8'
  },
    {
    label: '九级',
    value: '9'
  },
   {
    label: '十级',
    value: '10'
  }
]
const menuList = ref([
  {
    show: true,
    dataObject: 'StandardStatistics',
    dataObjectName: '数据保护标准',
    view: [
      {
        chartsType: 'Table',
        dataType: ['结构化资产', '非结构化资产'],
        others: ['所属组织机构', '所属应用系统']
      },
      {
        chartsType: 'Table',
        dataType: ['结构化资产'],
        others: ['所属组织机构', '所属应用系统']
      }
    ]
  }
])

const dataTypeMap = new Map([
  ['数据保护标准', 'template'],
  ['所属组织机构', 'dept'],
  ['所属应用系统', 'sys']
])

const tableData = [
  {
    // templateName: '',
    total: '合计',
    template1: 'template1',
    template2: 'template2',
    template3: 'template3',
    template4: 'template4',
    template5: 'template5',
    dept1: 'dept1',
    dept2: 'dept2',
    dept3: 'dept3',
    dept4: 'dept4',
    dept5: 'dept5',
    sys1: 'sys1',
    sys2: 'sys2',
    sys3: 'sys3',
    sys4: 'sys4',
    sys5: 'sys5'
  },
  // {
  //   templateName: '标准1',
  //   total: 'total',
  //   template1: 'template1',
  //   template2: 'template2',
  //   template3: 'template3',
  //   template4: 'template4',
  //   template5: 'template5',
  //   dept1: 'dept1',
  //   dept2: 'dept2',
  //   dept3: 'dept3',
  //   dept4: 'dept4',
  //   dept5: 'dept5',
  //   sys1: 'sys1',
  //   sys2: 'sys2',
  //   sys3: 'sys3',
  //   sys4: 'sys4',
  //   sys5: 'sys5'
  // },
  {
    templateName: '标准1',
    total: 'total',
    template1: 'template1',
    template2: 'template2',
    template3: 'template3',
    template4: 'template4',
    template5: 'template5',
    dept1: 'dept1',
    dept2: 'dept2',
    dept3: 'dept3',
    dept4: 'dept4',
    dept5: 'dept5',
    sys1: 'sys1',
    sys2: 'sys2',
    sys3: 'sys3',
    sys4: 'sys4',
    sys5: 'sys5'
  },
  {
    templateName: '标准1',
    total: 'total',
    template1: 'template1',
    template2: 'template2',
    template3: 'template3',
    template4: 'template4',
    template5: 'template5',
    dept1: 'dept1',
    dept2: 'dept2',
    dept3: 'dept3',
    dept4: 'dept4',
    dept5: 'dept5',
    sys1: 'sys1',
    sys2: 'sys2',
    sys3: 'sys3',
    sys4: 'sys4',
    sys5: 'sys5'
  },
  {
    templateName: '标准1',
    total: 'total',
    template1: 'template1',
    template2: 'template2',
    template3: 'template3',
    template4: 'template4',
    template5: 'template5',
    dept1: 'dept1',
    dept2: 'dept2',
    dept3: 'dept3',
    dept4: 'dept4',
    dept5: 'dept5',
    sys1: 'sys1',
    sys2: 'sys2',
    sys3: 'sys3',
    sys4: 'sys4',
    sys5: 'sys5'
  }
]
const SpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 第一列合并单元格（标题：数据保护标准）
  if (columnIndex === 0) {
    if (rowIndex % tableData.length === 0) {
      return {
        rowspan: tableData.length,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (columnIndex === 1) {
    // 第二列合并单元格（各个数据保护标准（四个为一组））
    if (rowIndex === 0) {
      return {
        rowspan: 1,
        colspan: 1
      }
    } else if ((rowIndex - 1) % 4 === 0) {
      return {
        rowspan: 4,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption
const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

const CloseChart = (objIndex, chartIndex) => {
  menuList.value[objIndex].temp.splice(chartIndex, 1)
}

// 拖动目录
const dragTable = () => {
  const el: any = document.getElementById('draggable-box')
  Sortable.create(el, {
    animation: 200,
    chosenClass: 'chosenClass', // 被选中项的css 类名
    onEnd: (evt) => {
      let { oldIndex, newIndex } = evt
      menuList.value.splice(newIndex, 0, menuList.value.splice(oldIndex, 1)[0])
      const arr = menuList.value.slice(0)
      menuList.value = []
      nextTick(() => {
        menuList.value = arr
        console.log('menuList.value', menuList.value)
        setTimeout(() => {
          dragTable()
        }, 1000)
      })
    }
  })
}

// 拖动目录中的图表
const dragChart0 = () => {
  const el: any = document.getElementById(`chart-box0`)
  if (!el) {
    return
  }
  Sortable.create(el, {
    group: 'shared',
    animation: 200,
    filter: '.Table-css',
    chosenClass: 'chosenClass', // 被选中项的css 类名
    onEnd: (evt) => {
      const { newIndex, oldIndex } = evt
      menuList.value[0].view.splice(newIndex, 0, menuList.value[0].view.splice(oldIndex, 1)[0])
      const arr = menuList.value.slice()
      menuList.value = []
      nextTick(() => {
        menuList.value = arr
        // 解决数组改变后拖动失效问题
        setTimeout(() => {
          dragChart0()
        }, 1000)
      })
    }
  })
}
const dragChart1 = () => {
  const el: any = document.getElementById(`chart-box1`)
  if (!el) {
    return
  }
  Sortable.create(el, {
    group: 'shared',
    animation: 200,
    filter: '.Table-css',
    chosenClass: 'chosenClass', // 被选中项的css 类名
    onEnd: (evt) => {
      const { newIndex, oldIndex } = evt
      menuList.value[1].view.splice(newIndex, 0, menuList.value[1].view.splice(oldIndex, 1)[0])
      const arr = menuList.value.slice()
      menuList.value = []
      nextTick(() => {
        menuList.value = arr
        // 解决数组改变后拖动失效问题
        setTimeout(() => {
          dragChart1()
        }, 1000)
      })
    }
  })
}
const dragChart2 = () => {
  const el: any = document.getElementById(`chart-box2`)
  if (!el) {
    return
  }
  Sortable.create(el, {
    group: 'shared',
    animation: 200,
    filter: '.Table-css',
    chosenClass: 'chosenClass', // 被选中项的css 类名
    onEnd: (evt) => {
      const { newIndex, oldIndex } = evt
      menuList.value[2].view.splice(newIndex, 0, menuList.value[2].view.splice(oldIndex, 1)[0])
      const arr = menuList.value.slice()
      menuList.value = []
      nextTick(() => {
        menuList.value = arr
        // 解决数组改变后拖动失效问题
        setTimeout(() => {
          dragChart2()
        }, 1000)
      })
    }
  })
}

const confirm = async () => {
  const composing = JSON.stringify(menuList.value)
  const data = await reportManageApi.reportManageCreate({
    ...preData.value,
    composing,
    defaultQuery: JSON.stringify(defaultQuery.value)
  })
  if (data) {
    ElMessage.success('操作成功')
    router.push({
      path: '/report/reportManage'
    })
  }
}
const updateReport = async () => {
  const composing = JSON.stringify(menuList.value)

  const data = await reportManageApi.reportManageUpdate({
    ...reportData.value,
    composing,
    defaultQuery: JSON.stringify(defaultQuery.value)
  })
  if (data) {
    ElMessage.success('操作成功')
    router.push({
      path: '/report/reportManage'
    })
  }
}
const cancel = () => {
  router.push({
    path: '/report/reportManage',
    query: {
      isFromEdit: 'true',
      ...preData.value
    }
  })
}

// 数据对象列表
const dataObjectList = ref()
const objectMap = new Map([
  ['StandardStatistics', '数据保护标准'],
  ['ClassificationStatistics', '类别'],
  ['LevelStatistics', '级别'],
  ['SystemStatistics', '所属应用系统'],
  ['DeptStatistics', '归属机构']
])
const getDataObject = async () => {
  const data = await reportManageApi.reportManageDataObject()
  console.log('data', data)
  dataObjectList.value = data
  data.forEach((item) => {
    objectMap.set(item.key, item.value)
  })
}

const getTempDetail = async () => {
  const data = await reportTempApi.reportTempGet({ id: route.query.tempId })
  menuList.value = data.context
}

const reportData = ref()
const getReportDetail = async () => {
  const data = await reportManageApi.reportManageGet({ id: route.query.id })
  // menuList.value = convertData(data.tempVO)
  menuList.value = JSON.parse(data.composing)
  defaultQuery.value = JSON.parse(data.defaultQuery)
  reportData.value = data
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, status: '1' })
  console.log('data', data)
  templateList.value = data
}
// 分类
const classificationList = ref([])
const getClassificationList = async () => {
  const data = await dataClassificationTree()
  classificationList.value = data
}
// 等级
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}
// 部门
const deptList = ref([])
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  deptList.value = data
}
// 系统
const systemList = ref([])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

onMounted(() => {
  getTemplateList()
  getClassificationList()
  getLevelList()
  getDeptList()
  getSystemList()
  // 获取数据类别下拉
  getDataObject()
  if (route.query.id) {
    // 获取报表详情
    getReportDetail()
  } else {
    // 获取模板详情
    getTempDetail()
  }

  setTimeout(() => {
    dragChart0()
    dragChart1()
    dragChart2()
    dragTable()
    // dragChart()
  }, 1000)
})
</script>
<style lang="scss">
.item {
  background: red;
}
.chart-wrap {
  width: calc(100% - 400px);
}
.chart-list {
  display: flex;
  flex-wrap: wrap;
}
.Table-css {
  width: 100%;
  margin-bottom: 12px;
  // height: 100px;
  // background-color: red;
}
.Pie-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: blue;
}
.Bar-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
.Line-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
</style>
